<?php
namespace Api\Controller;
use Think\Controller;
use Think\Upload;
use Think\Controller\RestController;
class BaseController extends RestController{
	public function securityTest(){
  	$uid = cookie('visitor_id');
  	if(!$uid){
  		$this->response(array('info'=>'未登录，或者未使用微信浏览器开启页面'),json,401);
  	}
  	return $uid;
  }
  //小程序获取openid
  public function getOpenid() {
    $code = $_GET['code'];//小程序传来的code值
    $appid = 'wxd5b5b1fe47f621fc';//小程序的appid
    $appSecret = '46f0f4cba95eb1963137adb64f1a93d7';// 小程序的$appSecret
    $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
    $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);
    $result = $this->curl_get($getUrl);
    $wxResult = json_decode($result, true);
    if (empty($wxResult)) {
      echo '获取openid时异常，微信内部错误';
    } else {
      $loginFail = array_key_exists('errcode', $wxResult);
      if ($loginFail) {
        var_dump($wxResult);
      } else {
        $result = $wxResult;
        // $data['open_id'] = $openid;
        // $info=M('tsc_member')->where($data)->find();
        // if(!$info){
        //   M('tsc_member')->add($data);
        // }
        $this->response(array('data' => $result), json, 200);
      }
    }
  }
  
  public function curl_get($url, &$httpCode = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
  }

  // 小程序解密手机号
  public function getWechatPhone() {
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)){
     $_POST = (array)json_decode(file_get_contents('php://input'), true);
    }
    $post = I('post.');
    if(!$post['session_key']||$post['session_key']==''){
      $this->jsonReturn(0,"缺少session_key");
    }
    if(!$post['encryptedData']||$post['encryptedData']==''){
      $this->jsonReturn(0,"缺少encryptedData");
    }
    if(!$post['iv']||$post['iv']==''){
      $this->jsonReturn(0,"缺少iv");
    }
    $appid = 'wxd5b5b1fe47f621fc';//小程序的appid
    $appSecret = '46f0f4cba95eb1963137adb64f1a93d7';// 小程序的$appSecret

    $result = $this->decryptData($post['encryptedData'],$post['iv'],$post['session_key']);
    $this->response(array('data' => $result), json, 200);
  }

  // 解密函数
  public function decryptData( $encryptedData, $iv, $session_key )
  {
    if (strlen($session_key) != 24) {
      return "session_key值错误";
    }
    $aesKey=base64_decode($session_key);
 
        
    if (strlen($iv) != 24) {
      return "iv值错误";
    }
    $aesIV=base64_decode($iv);
    $aesCipher=base64_decode($encryptedData);
    $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
 
    $dataObj=json_decode( $result );
    if( $dataObj  == NULL )
    {
      return "非法";
    }

    return $result;
  }

  // 获取用户session信息
  public function getUserSession(){
  	$userinfo = session('wechat_info');
  	if($userinfo){
  		return $userinfo['subscribe'];
  	}else{
  		return 'nodata';
  	}
  	
  }

  //检测是否工作人员
  public function workerTest(){
  	$openid = I('get.openid');
  	if(!$openid){
  		$this->response(array('info'=>'未登录，或者未使用微信浏览器开启页面'),json,400);
  	}
  	$re_user = M('visitor')->where(array('openid'=>$openid))->find();
  	$this->response(array('info'=>true),json,200);
  	// if($re_user['identity']==='1'){
  	// 	$this->response(array('info'=>true),json,200);
  	// }else{
  	// 	$this->response(array('info'=>false),json,200);
  	// }
  }

  public function registertest(){
  	$uid=$this->securityTest();
  	$data=M('user')->where("uid=$uid")->find();
  	$uid=$data['uid'];
  	if(empty($uid)){
  		$this->response(array('info'=>'未注册'),json,402);
  	}
  	return $uid;

  }

  public function processData(&$data, $model_name){
  	$model = M('Model')->getByName($model_name);
  	$fields = get_model_attribute($model['id'], false);
  	foreach ($fields as $key => $field){
  		if($field['type'] =='picture'){
  			$data[$field['name']] = $this->get_cover($data[$field['name']], 'path');
  		}elseif($field['type'] =='file'){
  			$data[$field['name']] = $this->get_cover_audio($data[$field['name']], 'savepath');
  		}
  	}
  }

  public function getLists($pid){
  	$list =M('category')->where(array('pid'=>$pid))->select();
  	if($list){
  		$this->response(array('info'=>$list),json,200);
  	}$this->response(array('info'=>"没找到相关信息"),json,400);
  }
  public function uploadPic(){
  	$config  =array(
		'mimes'    => '', //允许上传的文件MiMe类型
		'maxSize'  => 20*1024*1024, //上传的文件大小限制 (0-不做限制)
		'exts'     => 'jpg,gif,png,jpeg', //允许上传的文件后缀
		'autoSub'  => true, //自动子目录保存文件
		'subName'  => array('date', 'Y-m-d'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
		'rootPath' => './Uploads/Images/', //保存根路径
		'savePath' => '', //保存路径
		'saveName' => array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
		'saveExt'  => '', //文件保存后缀，空则使用原后缀
		'replace'  => false, //存在同名是否覆盖
		'hash'     => true, //是否生成hash编码
		'callback' => false, //检测文件是否存在回调函数，如果存在返回文件信息数组
		); //图片上传相关配置（文件上传类配置）
		$upload = new \Think\Upload($config);// 实例化上传类// 实例化上传类
		$image = new \Think\Image(); 
		$info   =   $upload->upload();
		if(!$info) {// 上传错误提示错误信息
			$error =$upload->getError();
			$this->response(array('status'=>0,'info'=>$error),json,400);
		}else{// 上传成功 获取上传文件信息
			$file =$info['file'];
			$newname ='new'.$file['savename'];
			$path = substr($config['rootPath'].$file['savepath'].$file['savename'],2);
			$newpath =substr($config['rootPath'].$file['savepath'].$newname,2);
			$source = imagecreatefromjpeg($path);
			$exif = exif_read_data($path);
			if(!empty($exif['Orientation'])) {
				switch($exif['Orientation']) {
					case 8:
					$source = imagerotate($source,90,0);
					break;
					case 3:
					$source = imagerotate($source,180,0);
					break;
					case 6:
					$source = imagerotate($source,-90,0);
					break;
				}
				imagejpeg($source,$path);
			}

			$image->open($path);
			$re =$image->thumb(300, 300,\Think\Image::IMAGE_THUMB_FIXED)->save($newpath);
		}
		$data =array('old_path'=>'/'.$path,'new_path'=>'/'.$newpath);
		return $data;
		
	}

	public function array_unique_fb($array2D){
		foreach ($array2D as $k =>$v){
			$v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
			$temp[] = $v;
		}
		$temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组
		foreach ($temp as $k => $v){
			$temp[$k] = explode(",",$v);   //再将拆开的数组重新组装
		}
		return $temp;
	}

	public function translate($object){ //$type:1对象 2数组
		//检查cookie 如果没有则默认中文
		if(!$object){
			return $object;
		}
		$language = cookie('language')?cookie('language'):2; //默认2简体中文 1En
		if($language==2){
			return $object;
		}

		$new = $object;
		$first = $object[0];
		if(!$first){
			foreach ($object as $key => $value) {
				# code...
				$tmp = substr($key,-3);
				if($tmp=='_en'){
					$new[substr($key,0,-3)] = $value;
				}
			}
		}else{
			foreach ($object as $key => $object_single) {
				# code...
				foreach ($object_single as $object_single_key => $value) {
					# code...
					$tmp = substr($object_single_key,-3);
					if($tmp=='_en'){
						$new[$key][substr($object_single_key,0,-3)] = $value;
					}
				}
			}
		}
		return $new;
	}






}